﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Tareas.ServiceReference;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Display;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;

namespace Tareas
{
    public sealed partial class SearchResultsPage
    {
        public SearchResultsPage()
        {
            InitializeComponent();
        }

        async void getProjectsByName(string search)
        {
            PageTitle.Text = "Proyectos (Cargando)";
            TaskServiceClient client = new TaskServiceClient();
            try
            {
                this.CollectionViewSource.Source = await client.getProjectByNameAsync(search);
                client.CloseAsync();
                PageTitle.Text = "Proyectos";
            }
            catch (Exception)
            {
                PageTitle.Text = "Se ha producido un error";
                //Show a Message dialog
            }
        }

        private UIElement _priorContent;
        UIElement PreviousContent
        {
            get { return _priorContent; }
            set
            {
                this._priorContent = value;
                BackButton.IsEnabled = value != null;
            }
        }

        void BackButton_Click(object sender, RoutedEventArgs e)
        {
            Window.Current.Content = PreviousContent;
            Window.Current.Activate();
        }

        public void Activate(SearchActivatedEventArgs args)
        {
            var queryText = args.QueryText;

            //TODO: Application-specific searching logic

            // Prepare bindable content
            var bindableProperties = new PropertySet();
            bindableProperties["QueryText"] = '"' + queryText + '"';
            bindableProperties["AllFilter"] = "All (0)";
            this.DataContext = bindableProperties;

            getProjectsByName(queryText);

            // Display the results
            this.PreviousContent = Window.Current.Content;
            Window.Current.Content = this;
            Window.Current.Activate();
        }

        // View state management for switching among Full, Fill, Snapped, and Portrait states

        private DisplayPropertiesEventHandler _displayHandler;
        private TypedEventHandler<ApplicationLayout, ApplicationLayoutChangedEventArgs> _layoutHandler;

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            if (_displayHandler == null)
            {
                _displayHandler = Page_OrientationChanged;
                _layoutHandler = Page_LayoutChanged;
            }
            DisplayProperties.OrientationChanged += _displayHandler;
            ApplicationLayout.GetForCurrentView().LayoutChanged += _layoutHandler;
            SetCurrentOrientation(this);
        }

        private void Page_Unloaded(object sender, RoutedEventArgs e)
        {
            DisplayProperties.OrientationChanged -= _displayHandler;
            ApplicationLayout.GetForCurrentView().LayoutChanged -= _layoutHandler;
        }

        private void Page_LayoutChanged(object sender, ApplicationLayoutChangedEventArgs e)
        {
            SetCurrentOrientation(this);
        }

        private void Page_OrientationChanged(object sender)
        {
            SetCurrentOrientation(this);
        }

        private void SetCurrentOrientation(Control viewStateAwareControl)
        {
            VisualStateManager.GoToState(viewStateAwareControl, this.GetViewState(), false);
        }

        private String GetViewState()
        {
            var orientation = DisplayProperties.CurrentOrientation;
            if (orientation == DisplayOrientations.Portrait ||
                orientation == DisplayOrientations.PortraitFlipped) return "Portrait";
            var layout = ApplicationLayout.Value;
            if (layout == ApplicationLayoutState.Filled) return "Fill";
            if (layout == ApplicationLayoutState.Snapped) return "Snapped";
            return "Full";
        }
    }
}
